'use client';

import { useClientParams } from '@/hooks';
import { staticGo } from '@/utils/common';
import {
  Divider,
  FormControlLabel,
  Menu,
  MenuItem,
  Radio,
  RadioGroup,
} from '@mui/material';
import { useEffect, useRef, useState } from 'react';

const baseSortData = [
  {
    title: 'Relevance',
    value: 'relevance',
    dir: [],
  },
  {
    title: 'Sales Volume',
    value: 'sales_volume',
    dir: [
      { title: 'Most to Least', value: 'desc' },
      { title: 'Least to Most', value: 'asc' },
    ],
  },
  {
    title: 'Price',
    value: 'price',
    dir: [
      { title: 'Lowest to Highest', value: 'asc' },
      { title: 'Highest to Lowest', value: 'desc' },
    ],
  },
  {
    title: 'Recently Added',
    value: 'approve_time',
    dir: [
      { title: 'Most Recent', value: 'desc' },
      { title: 'Least Recent', value: 'asc' },
    ],
  },
];

const ToolsBarSortMenu = () => {
  const { pathname, queryObject, basePath } = useClientParams();
  const defaultSelect =
    basePath == 'catalogsearch'
      ? { order: 'relevance', dir: '' }
      : basePath == 'new-arrivals'
        ? { order: 'approve_time', dir: 'desc' }
        : { order: 'sales_volume', dir: 'desc' };
  const initSortData =
    basePath == 'catalogsearch'
      ? [...baseSortData]
      : baseSortData.filter(e => e.value !== 'relevance');
  const [sortData, setSortData] = useState<any[]>(initSortData);
  const [selectedSort, setSelectedSort] = useState<Obj>({
    order: defaultSelect.order,
    dir: defaultSelect.dir,
    node: sortData[0],
  });
  const executeOnClose = false;
  const btnRef = useRef(null);
  const [open, setOpen] = useState(false);
  const tempRef: any = useRef<any>({});

  const rebuildList = ({ order, dir }: { order?: string; dir?: string }) => {
    const orderNode = sortData.find((od: any) => od.value == order);
    const orderBy = orderNode?.value || defaultSelect.order;
    const currNode = orderNode || sortData[0];
    const dirNode = currNode?.dir.find((di: any) => di.value == dir);
    const orderDir = dirNode?.value || currNode?.dir[0]?.value || '';
    const selected = { order: orderBy, dir: orderDir, node: currNode };
    // console.log(selected);
    setSelectedSort(selected);
    return selected;
  };
  const rebuildListRef = useRef(rebuildList);
  rebuildListRef.current = rebuildList;
  useEffect(() => {
    open && queryObject && rebuildListRef.current(queryObject);
  }, [queryObject, open]);

  const handleOpen = () => {
    setOpen(true);
    tempRef.prevState = selectedSort.order + '_' + selectedSort.dir;
  };
  const handleClose = (newSelected?: any) => {
    setOpen(false);
    if (executeOnClose) {
      const last = newSelected || selectedSort;
      const lastState = last.order + '_' + last.dir;
      if (tempRef.prevState != lastState) {
        setSelectedSort(last);
        changeQuery(last);
      }
    }
  };

  const handleSelectOrder = (e: any) => {
    const orderStr = e.target?.value;
    if (!orderStr) return;
    const orderNode = sortData.find((od: any) => od.value == orderStr);
    const dir = orderNode?.dir[0]?.value || '';
    const newSelected = rebuildListRef.current({ order: orderStr, dir: dir });
    if (!executeOnClose) changeQuery(newSelected);
  };
  const handleSelectDir = (e: any) => {
    const orderObj = e.currentTarget?.dataset;
    if (!orderObj) return;
    const newSelected = { ...selectedSort, dir: orderObj.dir };
    setSelectedSort(newSelected);
    if (executeOnClose) {
      handleClose(newSelected);
    } else {
      changeQuery(newSelected);
    }
  };
  const changeQuery = (newSelected: Obj) => {
    queryObject.p && delete queryObject.p;
    !newSelected.dir && delete queryObject.dir;
    newSelected.order == 'relevance' && delete queryObject.order;
    staticGo(pathname, {
      ...queryObject,
      ...(newSelected.order != 'relevance' ? { order: newSelected.order } : {}),
      ...(newSelected.dir ? { dir: newSelected.dir } : {}),
    });
  };

  return (
    <div>
      <button
        id="toolsbar_sort_button"
        className="toolsbar-sort-button"
        ref={btnRef}
        onClick={handleOpen}
      >
        <b className="iconfont icon-sort-default"></b>
        Sort
      </button>
      <Menu
        id="sort-menu"
        anchorEl={btnRef.current}
        open={open}
        onClose={() => handleClose()}
        MenuListProps={{
          'aria-labelledby': 'toolsbar_sort_button',
        }}
        className="toolsbar-sort-list"
      >
        <RadioGroup
          name="order-group"
          onChange={handleSelectOrder}
          value={selectedSort.order}
        >
          {sortData?.map((item: any, index: number) => (
            <MenuItem key={index}>
              <FormControlLabel
                value={item.value}
                control={<Radio />}
                label={item.title}
              />
            </MenuItem>
          ))}
        </RadioGroup>
        {selectedSort.node?.dir?.length > 0 && <Divider sx={{ my: '5px' }} />}
        {selectedSort.node?.dir.map((item: any, index: number) => (
          <MenuItem
            key={index}
            onClick={e => handleSelectDir(e)}
            selected={item.selected}
            data-dir={item.value}
            className={selectedSort.dir == item.value ? 'dir-selected' : ''}
          >
            <span className={'iconfont icon-sort-' + item.value}></span>
            {item.title}
          </MenuItem>
        ))}
      </Menu>
    </div>
  );
};

export default ToolsBarSortMenu;
